<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/15
 * Time: 9:49
 */

namespace app\controller\test;


use app\common\lib\Common;
use app\common\lib\Constant;
use app\common\lib\DetectFaceAdvance;
use app\common\lib\Guzzle;
use app\common\lib\MoyinTts;
use app\common\lib\Puppeteer;
use app\common\lib\QRCodeImage;
use app\common\lib\RabbitMq;
use app\common\lib\RedisQueue;
use app\common\lib\Spreadsheet;
use app\common\lib\TencentAsr;
use app\common\lib\TencentCos;
use app\common\lib\TencentIvld;
use app\common\lib\TencentTts;
use app\common\lib\VolcanoTts;
use app\controller\CoreController;
use app\exception\IndexException;
use app\model\banner\BannerModel;
use app\model\novel\NovelChapterPartModel;
use app\model\plan\BackgroundMusicModel;
use app\model\plan\PlanRoleTagModel;
use app\model\tencent\TimbreModel;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Psr7\MultipartStream;
use JamesHeinrich\GetID3\GetID3;
use support\Cache;
use support\Redis;
use support\Request;
use support\Response;
use Webman\Config;

class ToolController extends CoreController
{
    public function uploadLocalFile(Request $request)
    {
        $filePath = runtime_path('video_framerate3.mp4');
        $result = TencentCos::getInstance()->uploadLocalFile($filePath,'test');
        return $this->endSuccess($result);
    }

    public function uploadPartLocalFile(Request $request)
    {
        $filePath = runtime_path('video_framerate3.mp4');
        return $this->endSuccess(TencentCos::getInstance()->uploadPartLocalFile($filePath,'video'));
    }

    public function importMediaFile(Request $request)
    {
        $videoLink = 'https://ai-video-1320718644.cos.ap-guangzhou.myqcloud.com/video/local/test/20240315/mp4/912a3523971a2b1af2f8.mp4';

        $result = TencentIvld::getInstance()->importMediaFile($videoLink);
        return $this->endSuccess($result);
    }

    public function describeMedia(Request $request)
    {
        $mediaId = 'media-P9tVqUWM';
        //$mediaId = 'media-AlAr79A6';
        $result = TencentIvld::getInstance()->describeMedia($mediaId);
        return $this->endSuccess($result);
    }

    public function createTask(Request $request)
    {
        $mediaId = 'media-P9tVqUWM';
        $mediaId = 'media-AlAr79A6';
        $result = TencentIvld::getInstance()->createTask($mediaId);
        return $this->endSuccess($result);
    }

    public function describeTask(Request $request)
    {
        $taskId = 'task-FXK0vtp2';
        $taskId = 'task-8Hmcot4t';
        $taskId = 'task-W0yWi0jw';
        $taskId = 'task-HRcHoWkY';
        $result = TencentIvld::getInstance()->describeTask($taskId);
        return $this->endSuccess($result);
    }

    public function describeTaskDetail(Request $request)
    {
        $taskId = 'task-FXK0vtp2';
        $taskId = 'task-8Hmcot4t';
        $taskId = 'task-W0yWi0jw';
        $taskId = 'task-HRcHoWkY';
        $result = TencentIvld::getInstance()->describeTaskDetail($taskId);
        return $this->endSuccess($result);
    }

    public function ivldVideoDetail(Request $request)
    {
        set_time_limit(0);

        $param = [];
        if($request->file('file')->isValid()==false){
            throw new IndexException(4020,'上传失败');
        }

        $param['ext'] = $request->file('file')->getUploadExtension();

        if(in_array(strtolower($param['ext']),['mp4','avi','mov','wav'])==false){
            throw new IndexException(4020,'请上传视频');
        }

        $path = 'ivld';
        $lib = TencentCos::getInstance();
        $res = $lib->uploadLocalFile($request->file('file'),$path);
        $videoLink = 'https://'.$res['Location'];
        $result = TencentIvld::getInstance()->importMediaFile($videoLink);
        $mediaId = $result['MediaId'];
        while (true){
            $describeMedia = TencentIvld::getInstance()->describeMedia($mediaId);
            if(!empty($describeMedia['MediaInfo']['Status']) && $describeMedia['MediaInfo']['Status']==8){
                usleep(10000);
                break;
            }
            usleep(500000);
        }

        $taskResult = TencentIvld::getInstance()->createTask($mediaId);
        $taskId = $taskResult['TaskId'];

        while (true){
            $describeTask = TencentIvld::getInstance()->describeTask($taskId);
            if(!empty($describeTask['TaskInfo']['TaskStatus']) && $describeTask['TaskInfo']['TaskStatus']==8){
                usleep(10000);
               break;
            }
            usleep(500000);
        }

        $taskDetail = TencentIvld::getInstance()->describeTaskDetail($taskId);

        return $this->endSuccess($taskDetail);
    }

    public function asyncUploadVideo(Request $request)
    {
        $param = [];
        $param['file'] = $request->file('file','');
        $param['path'] = $request->input('path','');
        $param['name'] = $request->input('name','');

        if($request->file('file')->isValid()==false){
            throw new IndexException('上传失败');
        }

        $param['ext'] = $request->file('file')->getUploadExtension();

        if(in_array(strtolower($param['ext']),['mp4','avi','mov','wav'])==false){
            throw new IndexException('请上传视频');
        }

        $path = 'video';
        $path .= !empty($param['path']) ? '/'.trim($param['path'],'/') : '';
        $name = round(microtime(true)*1000).uniqid();
        $filePath = $path.'/'.date('ymd').'/'.substr(md5($name),'-16').'.'.$param['ext'];
        Common::mkdirs(dirname(runtime_path($filePath)));
        $res = copy($request->file('file')->getRealPath(),runtime_path($filePath));
        if($res==false){
            throw new IndexException(4020,'上传失败');
        }
        unlink($request->file('file')->getRealPath());
        $uploadId = round(microtime(true)*1000).mt_rand(100000,999999);

        // 队列名
        $queue = 'asyncUploadVideo';
        // 数据，可以直接传数组，无需序列化
        $data = ['uploadid'=>$uploadId,'filepath'=>runtime_path($filePath)];
        // 投递消息
        Redis::send($queue, $data);

        return $this->endSuccess(['uploadid'=>$uploadId]);
    }

    public function getUploadVideoProgress(Request $request)
    {
        $progress = Cache::get('uploadfile_progress_'.$request->input('uploadid',''),[]);
        if(empty($progress)){
            $n = 1;
            while (true){
                usleep(100000);
                $progress = Cache::get('uploadfile_progress_'.$request->input('uploadid',''),[]);
                if($progress || $n>=4){
                    break;
                }
                $n++;
            }

            if(empty($progress)){
                throw new IndexException(4020,'上传uploadid不存在');
            }
        }

        if($progress['progress']<0){
            throw new IndexException(4020,'上传失败');
        }

        //$result = BannerModel::getInstance()->getWhere([['bannerid','in',[6,7,8,9]]])->get();
        return $this->endSuccess($progress);
    }

    public function getVideoLink(Request $request)
    {
        //抖音app分享
        $shareText = '1.25 复制打开抖音，看看【小鱼和小游的作品】让我开了眼界 他是真行啊 # 搞笑夫妻 # 婚后生... https://v.douyin.com/iNv7dMBd/ 04/03 E@h.bn Okc:/';
        //抖音pc分享
        $shareText = '2.51 tEU:/ 07/26 a@a.At 让我开了眼界 他是真行啊 # 搞笑夫妻 # 婚后生活 # 你们的男友也是这样吗 # 万万想不到 # 离谱  https://v.douyin.com/iFJDHJNU/ 复制此链接，打开Dou音搜索，直接观看视频！';

        //快手app分享
        $shareText = 'https://v.kuaishou.com/o6CwHu  斯诺克后继有人"斯诺克 "斯佳辉 该作品在快手被播放过221.8万次，点击链接，打开【快手】直接观看！';
        //快手pc分享
        $shareText = 'https://www.kuaishou.com/f/X-KqCixy12zX1bV';

        //哔哩哔哩app分享
        $shareText = '【【广州地铁那些事Ⅶ】那些或鲜为人知或广为流传的废弃预留你又知多少？挖掘广州地铁1、2、8号线的废弃预留-哔哩哔哩】 https://b23.tv/cGjy1HQ';
        //哔哩哔哩pc分享
        $shareText = '【【广州地铁那些事Ⅶ】那些或鲜为人知或广为流传的废弃预留你又知多少？挖掘广州地铁1、2、8号线的废弃预留】 https://www.bilibili.com/video/BV1zC41147vZ/?share_source=copy_web';

        //小红书app分享
        $shareText = '45 烈火狂歌发布了一篇小红书笔记，快来看吧！ 😆 cNtpZP49LFOovJu 😆 http://xhslink.com/Va22wC，复制本条信息，打开【小红书】App查看精彩内容！';
        //小红书pc分享
        $shareText = '80 【有意思吧 - 烈火狂歌 | 小红书 - 你的生活指南】 😆 HeEJKtLKGw2Esz1 😆 http://xhslink.com/hdUK4E';

        //新浪微博app分享
        $shareText = 'https://video.weibo.com/show?fid=1034:5016939945197602';
//        //新浪微博pc分享
//        $shareText = 'http://t.cn/A6joL2EQ';
//
        //西瓜app分享
        $shareText = 'https://v.ixigua.com/iFJUpJcL/点击链接直接打开';
        //西瓜pc分享
        $shareText = 'https://www.ixigua.com/7341817709371654697';

        //头条app分享
        $shareText = 'https://m.toutiao.com/is/iNTBn7SQ/ - 谢谢国航，看看飞机上白金卡大佬的服务，乘务长亲自来问候#空姐 - 今日头条 - 今日头条';
        //头条pc分享
        $shareText = 'https://www.toutiao.com/video/7323902941042213415/';
//
        //好看app分享
        $shareText = 'https://haokan.hao123.com/v?vid=11846885951787884548&pd=haokan_share&context=%7B%22cuid%22%3A%22l8HRa_a3Hagx8H80la2N8j8QvagQaH8xga-Qa_ugHf8jkLag_iS6azAPA%22%7D';
        //好看pc分享
        $shareText = 'https://haokan.baidu.com/v?vid=12849841621539735246&';


        $preg = '/http[s]?:\/\/[\w|\/|\.|\-|=|\?|:|%|&]+/';
        preg_match_all($preg,$shareText,$data);

        $videoLink = '';
        if(!empty($data[0][0])){
            $url = $data[0][0];
            if(strpos($url,'douyin.com/')){
                $videoLink = Puppeteer::getInstance()->douyinVideoByMobile($url);
            }elseif(strpos($url,'kuaishou.com/')){
                $videoLink = Puppeteer::getInstance()->kuaishouVideoByPc($url);
            }elseif(strpos($url,'b23.tv/') || strpos($url,'bilibili.com/')){
                $videoLink = Puppeteer::getInstance()->bilibiliVideoByMobile($url);
            }elseif(strpos($url,'xhslink.com/')){
                $videoLink = Puppeteer::getInstance()->xiaohoneshuVideoByPc($url);
            }elseif(strpos($url,'video.weibo.com/') || strpos($url,'t.cn/')){
                $videoLink = Puppeteer::getInstance()->weiboVideoByApi($url);
            }elseif(strpos($url,'ixigua.com/')){
                $videoLink = Puppeteer::getInstance()->xiguaVideoByMobile($url);
            }elseif(strpos($url,'toutiao.com/')){
                $videoLink = Puppeteer::getInstance()->toutiaoVideoByPc($url);
            }elseif(strpos($url,'hao123.com/') || strpos($url,'baidu.com/')){
                $url = str_replace('baidu.com','hao123.com',$url);
                $videoLink = Puppeteer::getInstance()->haokanVideoByPc($url);
            }
        }
        var_dump($videoLink);

        return $videoLink;
    }

    public function stableDiffusionAPI(Request $request):Response
    {
        $param = [
            'prompt'=>'A girl buys items in the supermarket,realistic,absurdres,The scene is China',
            'negative_prompt'=>'(worst quality:1.6),(low quality:1.6),  (bad_prompt:0.8),  badhandv4, EasyNegative, EasyNegativeV2, ng_deepnegative_v1_75t',
            'sampler_name'=>'DPM++ SDE Karras',
            'sampler_index'=>'DPM++ SDE Karras',
            'seed'=>'-1',
            'steps'=>'20',
            'clip_skip'=>'2',
            'batch_size'=>'1',
            'cfg_scale'=>'7',
            'denoising_strength'=>'0.7',
            'hires_upscale'=>'2',
            'hires_upscaler'=>'Latent (antialiased)',
            'alphas_cumprod'=>'True',
            'Version'=>'v1.8.0',
            'width'=>'600',
            'height'=>'800',
            'override_settings'=>[
                'sd_model_checkpoint'=>'OIA Illustrator_0.10.safetensors [3328078dcc]',
                'sd_vae'=>'vae-ft-mse-840000-ema-pruned.safetensors'
            ],
            'tiling'=>false,
            'alwayson_scripts'=>[
                'controlnet'=>[
                    'args'=>[
                        [
                            'control_mode'=>'',
                            'enabled'=>true,
                            'guidance_start'=>'0',
                            'guidance_end'=>'1',
                            'input_image'=>base64_encode(file_get_contents(runtime_path('input_image.png'))),
                            'lowvram'=>false,
                            'model'=>"None",
                            'module'=>"none",
                            'pixel_perfect'=>true,
                            'processor_res'=>0,
                            'resize_mode'=>'Crop and Resize',
                            'threshold_a'=>0,
                            'threshold_b'=>0,
                            'weight'=>1,
                        ]
                    ]
                ]
            ],

        ];
        $headers = [
            'Authorization'=>'Basic dHVpd2VuOlJrSWopWCdZYWh6TGRIcUI=',
            'content-type'=>'application/json'
        ];
        $result = Guzzle::post('http://8.149.132.225:9999/','sdapi/v1/txt2img',$param,$headers,'json');
        if(!empty($result['images'])){
            foreach($result['images'] as $k=>$image){
                file_put_contents(runtime_path('stable_diffusion_test_'.$k.'.png'),file_get_contents('data:image/png;base64,'.$image));
            }
        }

        return json($result);
    }

    public function getTencentTts()
    {
//        preg_match_all('/\d+/','高566温天气894持续20天后，',$data);
//        var_dump($data);
//        $result = Common::numToChinese(48945665265);
//        return json([$result]);

        $text = '在未来的世界里，^人类已经成功地实现了太空旅行和星际探索。';
        $text = mb_substr($text,0,150);
        $option = [
            'volume'=>5,
            'voiceId'=>101001,
            'codec'=>'mp3',
        ];
        $result = TencentTts::getInstance()->textToVoice($text,$option);
        file_put_contents(runtime_path('TencentTts'.'.mp3'),file_get_contents('data:audio/mpeg;base64,'.$result['Audio']));

//        while (true){
//
//        }
//        $result = TencentTts::getInstance()->describeTtsTaskStatus($result['Data']['TaskId']);
        return json($result['Subtitles']);
    }

    public function getChatGpt()
    {
        $content = '课堂上，我忍不住玩弄楔花内衣的绷带，谁知内衣质量太差，竟被我一下扯断。绷带击中皮肤的声音瞬间引起了全班同学的注意。看着楔花眼中的杀意，我知道这一次回家又要被父亲收拾，因为楔花和我是从小玩到大的青梅竹马，放学肯定去我家打小报告，反正都要挨揍。我狠心直接将她拥入怀中，强吻了他，并在他耳边轻轻说道，这一辈子我不会再错过你了。上一世我虽是亿万不豪，但在患绝症之时才清楚身边人的真正面目。妻子为了得到我的家产，以刚出生的儿子为要挟。直到临死前，我看了律师给我的日记本，才知道青梅暗恋了我十六年，更是在我病情恶化的时候偷偷捐献骨髓给我。可能是老天知道我的不甘心，让我重生到十八岁，我发誓这一次一定要让她做我老婆。喂，你傻了吗？一直看着我干嘛？我从愣神中醒来，猛地一下站起身，将她抱在怀中，狠狠的吻了上去。这一瞬间，全班同学都发出嘘的一声，刘宇轩满脸通红，一把将我推开，然后一个过肩摔，将我摔倒在地，骑在我身上，控制着我的手臂，顾成你脑子进水了吗？为什么占我便宜？看着他那羞红了的脸颊，我随意编了个理由给糊弄了回。

在我们争吵后没多久，老师来到了教室，忽然一根粉笔朝我飞了过来，顾晨发什么呆上来做题，同学纷纷扭头都等着看我的笑话。我微微一笑，大步走向讲台，拿起粉笔就把答案写了出来，然后在众目睽睽之下回到座位上。刘宇轩递给我一个纸条，大混蛋，不错了，居然答对了。我也朝着他回了一个纸条，看到纸条后，他脸色一红，瞪了我一眼后便再没理我。放学后，刘宇轩慌忙的收拾完书包便跑离了教室，本以为他是不好意思面对，结果等我准备回家时才发现车胎被人放了弃。这时刘宇轩的声音幽幽的传来，哎，顾城，你的车子是不是没气了呀？真可惜，今天你只能走路回家了。听他那幸灾乐祸的口气就知道是他做的。我一把跳上他后座，紧紧的抱着他，快带我回家，他抓住我的手就咬上去，爱哟，刘大楔花开始打情骂俏，在听到周围的议论声后，他马上放开了嘴，回去再收拾你，不得不说你的小蛮腰是真的，行，这么抱着刚刚好，死不成，再说我就把你甩出去，别生气了，雨轩，我请你吃老冰棍，小区门口的小卖部王姨来两个雪糕。雨轩吃着他手中的雪糕，一脸享受的模样，吃完之后还有点异油。

胃镜的盯着我手里剩下的那半口，给我咬一口吧，顾城，就一口，好吧，就给你咬一口，别太大口了，简直他直接咬掉了大半根，就给我剩一点点，然后转身就开溜。我看着谨慎一点的雪糕，一把塞进嘴里追了上去，吃完我的雪糕还想跑，我轻笑一声，将他堵在楼梯道，你想干啥？他有点慌张的看着我，肉嘟嘟的脸颊红扑扑的说，吧，你该怎么赔偿我？你想屁吃还问我要补偿？今天你占我便宜，还没跟你算账呢。看着她那白皙的肌肤，不禁让我有些恍惚，顾成你妈来了？我摇了摇头，根本不信，正当我准备再次亲吻雨轩时，不然一只手揪住我的你又在欺负小溪了阿哟腾腾骂我没有，不信你问刘雨轩，刘雨轩则是一脸委屈的模样，阿姨，她，她没有欺负我，好啊，你小子现在学会威胁人了是吧？萱萱，你别怕，我回去就收拾他好的，那阿姨我先走了。说完他便一溜烟的跑上了楼。在吃过饭回到房间后，我拉开窗户朝对面喊，刘宇轩，你在干嘛？没一会儿，对面的窗户打开，死孤城，叫我干啥？你是不是在偷偷骂我？你怎么知道？果然在骂我？你喜欢怎么样的男生？他思索片刻说，没想。

不过应该要帅一点的，那不就是我吗？你的脸皮还真是比城墙都红，嘿嘿，你叫我过来就只是想要这些，真无聊啊。现在轮到我问你，他趴在窗户上看着我，你未来女朋友的标准是什么样的？我未来女朋友身高一米六十五，体重八十斤左右，鞋码三十二，皮肤白皙，长得漂亮，O型血的他们会一阵好你的顾程又拿我开涮。说罢便拉上了窗帘，结束了这场对话，然后便盯着眼前的作业本开始发呆，脑海中忽然浮现出记忆深刻的画廊。那一年，我们六组房间里，我正坐在地上，专心致志的摆弄着积木玩具。刘宇轩从外面小跑进来，来到我的面前，阿成，你想吃糖吗？这是喜酒的喜糖了。我看到糖果，两眼发光，擦了一把鼻涕。轩轩，我想吃，我想吃，他把糖塞到我的手里，妈妈说结婚的人才吃喜糖，你吃了以后要娶我，好，我娶你。次日清晨，顾大懒猪起床了。我起床走到窗边，看向对面的女孩，一阵傻笑。傻笑什么？还不快去换校服？我可不想陪你吃到。在去学校的路上，我俩拐进了一个小巷子，中药老板，两碗猪杂粉，今天我请你吃。顾宇轩用一种非常惊愕的目光看着我，以前都是怕我吃了不给钱的。

今天怎么这么大火，一定有阴谋。正在他发呆的时候，我开口问他，你怎么有黑眼圈了？是不是想我想的夜不能寐？你想的美啊，傻子才想你，我只是没写完作业惦记着而你，哪有人这么说自己呢？顾宇轩撅着嘴，你才是傻子，本姑娘智商一百一十五好呢是吗？那我考考你二乘四等于多少八爱好闺女顾辰你大爷的。说罢就要伸手和我开撕，别激动啊，大庭广众的影响多不好，等回到家里随便收拾我，混蛋臭不成，看我回去怎么收拾你。在一阵打闹中，我们来到了学校，现在距离高考仅剩两个月，每天除了模拟测试就是模拟考试，很是无聊，今天倒是很例外，没想到最后一节课是自习，我从裤兜里掏出几张皱巴巴的一块钱，数来数去，零花钱只剩下八块，这点钱不够给刘宇轩买生日礼物了，最终还是打起了胖虎的主，铁子，走，我带你去挣钱。说罢便带着胖虎翘课去了电脑城。看着我提前翘课，刘宇轩一个人生起了闷气，哼，不凑不成，我自己回去电脑城的一处维修店面砖，一个青年正抱着电脑与老板发生了争执，什么？修个电脑需要二十天，这也太久了吧，没有其他快速的办法。

要不然我就找工商投诉，声音很大，马上引起了我的注意，电脑是坏了吗？要不给我来试试？我会修电脑？胖老板上下打量着穿着校服的我，一脸不信的样子，我专门学过修电脑，言语中没有透露着一丝的紧张。听到我会修电脑，青年像抓到了救命稻草一样，你来试试看吧，我今晚和别人约定好吧，一起组团打游戏。没一会儿的功夫，我便找出了这台电脑的毛病，然后再征得老板的允许后，便开始拆解起了电脑。大约一个小时的时间，电脑成功开机，谢谢了，小兄弟，你真是帮了我一个大忙，我叫杨建，留个联系方式吧，以后弱坏了还找你。然后他便从口袋里掏出了六百块钱交给你，要知道，那个时期的六百块钱可是一个职工干一个月的工资。胖老板舔着脸过来，满脸笑容的对我说，兄弟，手艺不错呀，有没有兴趣和我合作呀？我这里的订单都交给你，赚到的钱五五分怎么样？我当场拒绝了，利润五五开的了，那我只能去电子大厦那里跟其他老板合作。话说完就准备走，老板赶忙将我拉住，你觉得五五开不行，那怎么分合适？二八开我八你二，能接受就合作，不能接受拉倒。说罢，你就又准备朝着门外走去，二八开就二八开。

这时我才露出一抹微笑，合作愉快，老板在离开电脑城后，我拿着钱就带着胖虎直奔福田市场而去。此刻的刘宇轩正趴在书桌上望着我家的窗户，臭不成还没回来吗？随即便拿起晾衣杆捅了捅我那紧闭的窗户，嘎吱，他身后的门打开，雨轩，你在干什么？他被吓一跳，连忙把晾衣杆收回。没，没什么。李婉一眼就看穿了他的心思，萱萱，你是不是喜欢顾晨啊？妈，你说什么呢？我才没有喜欢他，傻瓜才喜欢他。李婉看到他窘迫的模样，掩嘴偷笑。我看顾晨挺好的，不但善良，而且挺机灵的。刘宇轩咬了一口苹果，他哪里好了，成天就知道欺负我，欺负我，我可不信。说罢，李婉便走进了厨房开始做饭。轰隆隆，忽然窗外电闪，密云密布，雨水如豆子一般噼里啪啦打了伞，顾晨好像没带雨伞。刘宇轩越想越是担心，于是拿着伞就跑出了门。李婉从厨房里伸出脑袋，嘴角露出一抹笑容，孩子脸上不关心顾晨，其实心里比谁都关心。他撑着伞来到职工小区门口，往路口方向张望，在这儿一等就是半个多小时。忽然一辆自行车在路口出现，顾晨，你跑哪去了？怎么这么晚才回来？

我没想到会下暴雨，就在外面躲了一会，嘿嘿，难道你是特意在等我？才没有呢？我在等我爸。他脸颊一红，眼中有几分慌张，连忙转移话题，你不是有雨衣吗？为什么抱着不穿？我咧着嘴嘿嘿一笑，那是送你的生日礼物啊，顾雨轩镇住，可下下周的周六才是我生日啊，没关系，我送你两次。说罢，你便将雨衣掀开，一只一米三高的粉红小猪王出现在他的眼前，提前祝你生日快乐，他有些惊愕的看着我，心头一震，这个傻子，为了不淋湿这个王红，宁愿自己淋着雨回来，只是因为这是送给我的生日礼物。他的心里是既惊喜又感不喜欢吗？喜欢，喜欢这个颜色吗？喜欢，喜欢这个款式吗？喜欢，喜欢我吗？喜欢你又占我便宜。';
        $content = str_replace(["\n","\r"],[""],$content);
        $contentString = Common::contentBatchPart($content);
        return json([$contentString]);
        //$content = mb_substr($content,0,300);
        file_put_contents(runtime_path('content.txt'),$content);
       // var_dump(mb_strlen($content));
        $promt = <<<EOD
Divide the following article into small paragraphs, each of 30 Chinese characters or less.
The divided paragraphs should maintain coherence and necessary content integrity, the information should be complete,
and the original text should not be altered. This way each paragraph can be read independently, 
but not as a complete independent sentence or paragraph. Note: When splitting, 
please be sure to maintain the coherence and information integrity of the article content to avoid possible loss of information. 
Each paragraph should be 30 Chinese characters or less. The article content is as follows:
EOD;
        $param = [
            'model'=>'gpt-4o',
            'messages'=>[
               [
                    'role'=>'user',
                    'content'=>$promt."\n".$content
                ],

            ],
        ];
        $header = [
            'Authorization'=>config('param.zizengzeng_token'),
            'Content-Type'=>'application/json',
        ];
       // var_dump($param);
        $reuslt = Guzzle::post('https://flag.smarttrot.com/','v1/chat/completions',$param,$header,'json');

        file_put_contents(runtime_path('result.txt'),$reuslt['choices'][0]['message']['content']??'');
        return json($reuslt);
    }

    /**
     * 批量导入音色
     * @param Request $request
     * @return Response
     * @throws IndexException
     */
    public function batchImportTimbre(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $file = current($request->file());
            if ($file && $file->isValid()) {
                $ext = strtolower($file->getUploadExtension());
                if (!in_array($ext, ['xlsx'])) {
                    throw new IndexException(4020, '仅支持 xlsx格式');
                }
            }

            $data = Spreadsheet::getInstance()->readExcelFile($file->getRealPath());
            unset($data[1]);
            $insert = [];
            foreach($data as $key=>$val) {
                $val = array_map('trim', $val);
                $insert[] = [
                    'name'=>$val[1],
                    'timbreid'=>$val[0],
                    'scenes'=>$val[2],
                    'trait'=>$val[3],
                    'lang'=>$val[5],
                    'tone_rate'=>$val[6],
                    'emotion'=>$val[7],
                    'isgood'=>1,
                ];
            }

            $result = TimbreModel::getInstance()->insert($insert);

            return json([$result]);
        }
    }

    public function getChatGptPromto()
    {
        $content = file_get_contents(runtime_path('promto'));
        $content .= '我是不婚主义者，但没敢跟我妈说。,临近过年，我妈玩命地给我安排相亲，连续相了10天的亲后，我给发小江北辰打电话。';
        $param = [
            'model'=>'gpt-4o',
            'messages'=>[
                [
                    'role'=>'system',
                    'content'=>$content,
                ],
            ],
        ];
        $header = [
            'Authorization'=>config('param.zizengzeng_token'),
            'Content-Type'=>'application/json',
        ];
        $result = Guzzle::post('https://flag.smarttrot.com/','v1/chat/completions',$param,$header,'json');


        return json([$result]);

    }

    public function getChatGptPromto2()
    {

        while (true){
            $content = '我国女孩';
            $param = [
                'model'=>'impactframes/llama3_ifai_sd_prompt_mkr_q4km',
                'prompt'=>$content,
                'stream'=>false,
            ];
            $header = [
                //'Authorization'=>config('param.zizengzeng_token'),,
                'Content-Type'=>'application/json',
            ];
            $result = Guzzle::post('http://8.149.132.225:11434/','api/generate',$param,$header,'json');

            var_dump($result);
        }


        return json([]);

    }

    public function getTencentAsr()
    {
        $str = '但也不差再次添量。\n[7:0.360,7:38.710]  两人都吃饱喝足准备出发。但也不差再次添量。\n[7:38.710,8:8.710]  两人都吃饱喝足准备出发。';
        $string = preg_replace(['/\[[\d|,|:|.]+\]/'],'',$str);
        return json([$string]);
        try{
            $url = 'https://ai-video-1320718644.cos.ap-guangzhou.myqcloud.com/video/test/baokuan/20240509/mp4/bd9697114d0c352ed347.mp4';
            $result = TencentAsr::getInstance()->createRecTask($url);
            return json($result);
        }catch (\Exception $e){
            return json(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
        }

    }

    public function addRedisQueue()
    {
        $k = 0;
        while (true){
            $k++;

            //生成唯一的请求id
            $requestId = Common::getRequestId();

            // 队列名
            $queue = 'asyncUploadVideo';
            // 数据，可以直接传数组，无需序列化
            $data = ['requestid' => $requestId, 'user_planid' => mt_rand(1000,9999)];
            // 投递消息
            RedisQueue::getInstance()->sendQueue($queue, $data);

            //生成唯一的请求id
            $requestId = Common::getRequestId();

            // 队列名
            $queue = 'asyncUploadVideo2';
            // 数据，可以直接传数组，无需序列化
            $data = ['requestid' => $requestId, 'user_planid' => mt_rand(1000,9999)];
            // 投递消息
            RedisQueue::getInstance()->sendQueue($queue, $data);
            if($k>=1){
                break;
            }

        }
        return json([]);
    }

    public function generateQrcode(Request $request)
    {
        return QRCodeImage::getInstance()->generateUserQrCode('https://tuiwen.qiepian.vip/register/');
    }

    public function getDouchachaData(Request $request):Response
    {
        $keyword = $request->input('keyword','推文');
        if($keyword=='短剧'){
            $keyword = '短剧';
            $cacheKey = 'douchacha_skit_data';
        }else{
            $keyword = '推文';
            $cacheKey = 'douchacha_tuiwen_data';
        }

        $url = 'https://www.douchacha.com/searchdetail?name='.$keyword;
        $fileName = 'getDouchachaData_cookie.txt';
        $cookiesData = [];
        if(is_file(runtime_path($fileName))){
            $cookie = file_get_contents(runtime_path($fileName));
            $cookies = explode(';',$cookie);
            foreach($cookies as $val){
                $val = trim($val);
                $key = substr($val,0,strpos(trim($val),'='));
                $value = substr($val,strpos(trim($val),'=')+1);
                $cookiesData[$key] = $value;
            }
        }
        //var_dump($cookiesData);exit;

        $ql = \QL\QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(\QL\Ext\Chrome::class);
        // 或者自定义注册的方法名
        $ql->use(\QL\Ext\Chrome::class, 'chrome');

        $userAgents = [
            'User-Agent,Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'User-Agent,Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'User-Agent,Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;',
            'User-Agent,Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
            'User-Agent,Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
            'User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
            'User-Agent,Mozilla/5.0 (Windows NT 6.1; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
            'User-Agent,Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
            'User-Agent,Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
            'User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
            'User-Agent,Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
            'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',
            ];

        $html = $ql->chrome(function ($page, $browser) use ($url,$cookiesData,$fileName,$userAgents) {
            $userAgent = $userAgents[rand(0,count($userAgents)-1)];
            $page->setUserAgent($userAgent);

            // 设置cookie
            $page->setCookie([
                'name' => 'BMAP_SECKEY',
                'value' => $cookiesData['BMAP_SECKEY']??'4xSU2gILlmj3651WXYdjMUgwNxLTeeSBr8wp-ATEzUWkbZDsQLIxN3Iho_0h10lPEbTLvFmH9lwm8bNzINll8CmHnNuLKPo77K11W19ki2Bxgurqgg_6Bnyg0wFOo_O3IAq8rkRstMtXqNvburZ_u4PR9BviMI-fKvYUm2glwt3gJwvHOBUeVisAvNar9hKInwysUNfTQHjaomSOpwpAtQ',
                'domain' => 'www.douchacha.com',
                'path' => '/'
            ],[
                'name' => 'SECKEY_ABVK',
                'value' => $cookiesData['SECKEY_ABVK']??'rKXij5D7h5QrDccu9RowVjZB9P+djFaiX0MNnpKsIUs%3D',
                'domain' => 'www.douchacha.com',
                'path' => '/'
            ],[
                'name' => 'dcc_sid',
                'value' => $cookiesData['dcc_sid']??'3cecf2d2-8d6e-4616-b16b-75c5ed893337',
                'domain' => 'www.douchacha.com',
                'path' => '/'
            ],[
                'name' => 'Hm_lvt_5e3b865d73ba569c052e9fb5792de511',
                'value' => $cookiesData['Hm_lvt_5e3b865d73ba569c052e9fb5792de511']??'1715828137,1715933338',
                'domain' => 'www.douchacha.com',
                'path' => '/'
            ],[
                'name' => 'Hm_lpvt_5e3b865d73ba569c052e9fb5792de511',
                'value' => $cookiesData['Hm_lpvt_5e3b865d73ba569c052e9fb5792de511']??'1715935356',
                'domain' => 'www.douchacha.com',
                'path' => '/'
            ]);

            $page->setViewport(['width' => 1500, 'height' => 950]);

            $page->goto($url);

            //设置本地存储 localStorage
            $token = $page->evaluate(\Nesk\Rialto\Data\JsFunction::createWithBody(
                "
                window.localStorage.setItem('token','eyJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoiUEMiLCJleHAiOjE3MTg1MzM5NjksInVzZXJJZCI6MTczNzQyNjAzNTM3NDQzNjM1MiwiY3JlYXRlRGF0ZSI6IjIwMjQtMDUtMTcgMTg6MzI6NDkifQ.MZGlNM0ap0aQFhzCTzNKT5Ovurw9IG1NQ7FK0VsdSt4');
                window.localStorage.setItem('MIAO_LID','c060e863b823d3e95823fae71172d954881caa6f_1715828137');
                window.localStorage.setItem('d_m_p','3571be79-f7f0-4185-8dd6-d24ce7329b60');
                window.localStorage.setItem('Hm_lvt_5e3b865d73ba569c052e9fb5792de511','1747477992325|1715828137,1715933338');
                window.localStorage.setItem('uid','1737426035374436352');
                window.localStorage.setItem('PstartTime','1716175414865');
                window.localStorage.setItem('captcha_webworker_supported','2');
                window.localStorage.setItem('dt','1716177505533');
                window.localStorage.setItem('open_page_again_time','1717124139594');
                window.localStorage.setItem('setRefToken','eyJhbGciOiJIUzUxMiJ9.eyJ0eXBlIjoiUEMiLCJleHAiOjE3MjExMjU5NjksInVzZXJJZCI6MTczNzQyNjAzNTM3NDQzNjM1MiwidG9rZW4iOiJleUpoYkdjaU9pSklVekkxTmlKOS5leUowZVhCbElqb2lVRU1pTENKbGVIQWlPakUzTVRnMU16TTVOamtzSW5WelpYSkpaQ0k2TVRjek56UXlOakF6TlRNM05EUXpOak0xTWl3aVkzSmxZWFJsUkdGMFpTSTZJakl3TWpRdE1EVXRNVGNnTVRnNk16STZORGtpZlEuTVpHbE5NMGFwMGFRRmh6Q1R6TktUNU92dXJ3OUlHMU5RN0ZLMFZzZFN0NCIsImNyZWF0ZURhdGUiOiIyMDI0LTA1LTE3IDE4OjMyOjQ5In0.ijE2R1qXOBlUGTOfVXDYoVNsYOB8LNT1YiLCny5G6U9NhWQWysPl8wOvzD5_RvT5npF_sta6ZxzwOoRcnNJA0w');
                window.localStorage.setItem('userInfo','{\"user_id\":\"1737426035374436352\",\"phone\":\"13021987009\",\"nick_name\":\"欢乐马\",\"head_img\":\"https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4hiaeQahVq3WR6SlWxdde0oMic68suwia09enZajb0XvibGpTD2cu30x9hq5PN5HI2R0h7ibo1pdDFjiaQ/132\",\"gender\":\"none\",\"grade\":\"SVIP\",\"pay_short_token\":\"6c57752907e04799ac73fb2561d45522\",\"grade_info\":{\"paused_day\":0,\"current_day\":2,\"current_grade\":\"SVIP\",\"current_grade_expire_time\":\"1716134399999\",\"service_time\":\"1715941993414\"},\"has_sub_account_verify\":false,\"has_sub_account_data\":false,\"register_time\":\"1703069621000\",\"permission_range\":[\"1715825674111\",\"1718467199999\"],\"invitation_code\":\"SM5VZX\",\"sub_count\":\"12\",\"show_original_data\":false,\"permission_version_code\":202401190,\"show_old\":false,\"old24\":false}');

                return window.localStorage.getItem('token');
               "
            ));

            //获取cookie
            $cookie = $page->evaluate(\Nesk\Rialto\Data\JsFunction::createWithBody("return document.cookie"));
            file_put_contents(runtime_path($fileName),$cookie);
            //var_dump($cookie);

            $dimensions = $page->evaluate(\Nesk\Rialto\Data\JsFunction::createWithBody("
                                document.addEventListener('keypress', function(event) {
                                    const key = event.key; // 获取按下的键名
                                    console.log('键被按下:', key);
                                    // 检查特定键是否被按下，例如空格键
                                    if (key === ' ') {
                                        console.log('空格键被按下');
                                    }
                                });
                          "));
            //var_dump($dimensions);

            $page->waitFor('.el-table__row');

            $i=0;
            sleep(3);
            while ($i<10){
                $i++;
                $page->keyboard->press('Space');
                sleep(1);
            }

            $html = $page->content();
            //$bodyHtml = $page->evaluate(\Nesk\Rialto\Data\JsFunction::createWithBody("return document.body.outerHTML"));
            //file_put_contents(runtime_path('getDouchachaData2_html.html'),$bodyHtml);

            //这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            sleep(20);
            $browser->close();

            // 返回值一定要是页面的HTML内容
            return $html;
        }, [
            'headless' => false, // 启动可视化Chrome浏览器,方便调试
            'devtools' => true, // 打开浏览器的开发者工具
            'args'     => ['--no-sandbox', '--disable-setuid-sandbox'],
        ])->getHtml();
        var_dump(mb_strlen($html));
//        $fileName = 'getDouchachaData.html';
//        file_put_contents(runtime_path($fileName), $text);

        //$html = file_get_contents(runtime_path($fileName));
        $data = \QL\QueryList::html($html)->rules([
            'image' => array('.el-table_1_column_1 .user_content .avatar_img','src'),
            'name' => array('.el-table_1_column_1 .user_count .name','text'),
            'user_tag' => array('.el-table_1_column_1 .user_count .user_tag','text'),
            'account' => array('.el-table_1_column_1 .user_count .user_level_box>p','text'),

            'fans_nums' => array('.el-table_1_column_2 span','text'),
            'video_nums' => array('.el-table_1_column_3 span','text'),
            'goods_video_nums' => array('.el-table_1_column_4 span','text'),
            'avg_like_nums' => array('.el-table_1_column_5 span','text'),
            'live_nums' => array('.el-table_1_column_6 span','text'),
            'goods_live_nums' => array('.el-table_1_column_7 span','text'),
            'avg_look_nums' => array('.el-table_1_column_8 span','text'),
            'avg_sale_amounts' => array('.el-table_1_column_9 span','text'),
        ])->range('.el-table__row')->query()->getData();
var_dump($data);
        $data = $data->all();
var_dump($data);
        if(!empty($data)){
            \support\Redis::connection('douchacha')->set($cacheKey,json_encode($data,256));
            //@unlink(runtime_path($fileName));
        }
        return json($data);
    }

    public function jsonString()
    {
        $prompt = '@prompt';
        $modelVal = '@model';
        $width = '@width';
        $height = '@height';
        $batchSize = '@batch_size';
        $param = [
            'prompt'=>$prompt,
            'negative_prompt'=>'EasyNegative,ng_deepnegative_v1_75t,(badhandv4:1.2),(worst quality:2),(low quality:2),(normal quality:2),lowres,bad anatomy,(bad hands),watermark,many fingers,(broken hands),nsfw,skin blemishes,(ugly:1.331),(duplicate:1.331),(morbid:1.21),(mutilated:1.21),mutated hands,(poorly drawn hands:1.5),(bad anatomy:1.21),(bad proportions:1.331),extra limbs,(disfigured:1.331),(extra legs:1.331),(fused fingers:1.61051),(too many fingers:1.61051),(unclear eyes:1.331),lowers,bad hands,missing fingers,extra digit,bad hands,missing fingers,(((extra arms and legs))),',
            'sampler_name'=>'DPM++ SDE Karras',
            'sampler_index'=>'DPM++ SDE Karras',
            'seed'=>'-1',
            'steps'=>'20',
            'clip_skip'=>'2',
            'batch_size'=>$batchSize??1,
            'cfg_scale'=>'7',
            'denoising_strength'=>'0.7',
            'hires_upscale'=>'2',
            'hires_upscaler'=>'Latent (antialiased)',
            'alphas_cumprod'=>'True',
            'Version'=>'v1.8.0',
            'width'=>$width??'600',
            'height'=>$height??'800',
            'override_settings'=>[
                'sd_model_checkpoint'=>$modelVal?:'OIA Illustrator_0.10.safetensors [3328078dcc]',
                'sd_vae'=>'vae-ft-mse-840000-ema-pruned.safetensors'
            ],
            'tiling'=>false,
            'alwayson_scripts'=>[
                'controlnet'=>[
                    'args'=>[
                        [
                            'guidance_start'=>'0',
                            'guidance_end'=>'1',
                            'input_image'=>base64_encode(file_get_contents(runtime_path('input_image.png'))),
                            'lowvram'=>false,
                            //'model'=>$modelVal?:'OIA Illustrator_0.10.safetensors [3328078dcc]',
                            'module'=>"reference_adain",
                            'pixel_perfect'=>true,
                            'processor_res'=>0,
                            'resize_mode'=>1,
                            'threshold_a'=>0,
                            'threshold_b'=>0,
                            'weight'=>1,
                        ]
                    ]
                ],
                'ADetailer'=>[
                    'args'=>[
                        [
                            'ad_model'=>'face_yolov8n.pt',
                            'ad_prompt'=>'detail face',
                            'ad_confidence'=>'0.7',
                            'ad_denoising_strength'=>'0.7',
                        ]
                    ]
                ]
            ],
        ];

        return json($param);
    }

    public function redisCache()
    {

//        $map = array_column(Constant::AI_IMAGE_SERVER_DOMAIN,null,'ip');
//        return json($map);
//        $aiImageServers = Constant::AI_IMAGE_SERVER_DOMAIN;
//        $ipServer = ['domain'=>'http://8.149.132.225:9999/','ip'=>'8.149.132.225'];
//        $endServer = [];
//        foreach ($aiImageServers as $k=>$val){
//            if($val['ip']==$ipServer['ip']){
//                $endServer = $val;
//                unset($aiImageServers[$k]);
//            }
//        }
//        array_push($aiImageServers,$endServer);
//        array_values($aiImageServers);
//        return json($aiImageServers);
//        Redis::connection('ai_image_cache')->set('dasdas_12.12.12.12','dasdasdasda');
//        $data = Redis::connection('ai_image_cache')->get('dasdas_12.12.12.12');
//        return json([$data]);



        $i=1;
        $queue = 'aiimage_queue';

        $queueData = Redis::connection('ai_image_cache')->lRange($queue,0,-1);
        var_dump($queueData);

        $package_str = json_encode([
            'id'=>1,
            'start_time'       => time(),
            'ip'=>'118.31.172.122',
            'data'     => []
        ]);
        Redis::connection('ai_image_cache')->lpush($queue,$package_str);

        $package_str = json_encode([
            'id'=>2,
            'start_time'       => time(),
            'ip'=>'118.31.172.122',
            'data'     => []
        ]);
        Redis::connection('ai_image_cache')->lpush($queue,$package_str);
        $package_str = json_encode([
            'id'=>3,
            'start_time'       => time(),
            'ip'=>'118.31.172.122',
            'data'     => []
        ]);
        Redis::connection('ai_image_cache')->lpush($queue,$package_str);
        $package_str = json_encode([
            'id'=>4,
            'start_time'       => time(),
            'ip'=>'118.31.172.122',
            'data'     => []
        ]);
        Redis::connection('ai_image_cache')->lpush($queue,$package_str);

        $index = Redis::connection('ai_image_cache')->llen($queue);
        $queueData = Redis::connection('ai_image_cache')->lRange($queue,0,-1);
        $queueData = array_reverse($queueData);
        //$queueData = json_decode($queueData[0], true);
        $queueRow = Redis::connection('ai_image_cache')->rPop($queue);
        return json([$index,$queueData,$queueRow]);
    }

    public function batchUploadPlanRoleTag()
    {
        $content = file_get_contents(runtime_path('keyword.json'));
        $contents = json_decode($content, true);
        $insert = [];
        foreach($contents as $key=>$content){
            foreach($content as $k=>$con){
                foreach($con as $c){
                    $insert[] = [
                        'name'=>$c['zh'],
                        'en_name'=>$c['en'],
                        'level1_name'=>$key,
                        'level2_name'=>$k,
                    ];
                }
            }
        }

        PlanRoleTagModel::getInstance()->insert($insert);

        return $this->endSuccess(0);
    }

    public function moyinTts()
    {
        $text = '魏胖告诉我，这家伙视力2。0';
        $option = [
            'speed'=>'1',
            'volume'=>'10',
            'speaker'=>'mercury_xiaomeng',
        ];
        $result = MoyinTts::getInstance()->textToVoice($text,$option);
        file_put_contents(runtime_path('mouyin_tts50.mp3'),$result['content']);
        return json($result['srt_address_data']??[]);
//        $srtAddess = array_filter(explode("\n",file_get_contents(runtime_path('srt.srt'))));
//        $srtAddessDatas = array_chunk($srtAddess,3);
//        $srtAddessData = [];
//        foreach($srtAddessDatas as $srtAddessRow){
//            $row = [];
//            $srtArr = explode('-->',$srtAddessRow[1]);
//
//            //开始时间
//            $startTimeArr = explode(',',trim($srtArr[0]));
//            $startTimeHis = explode(':',$startTimeArr[0]);
//            $row['utime']['start'] = round(($startTimeHis[0]*3600)+($startTimeHis[1]*60)+$startTimeHis[2])*1000+$startTimeArr[1];
//
//            //结束时间
//            $startTimeArr = explode(',',trim($srtArr[1]));
//            $startTimeHis = explode(':',$startTimeArr[0]);
//            $row['utime']['end'] = round(($startTimeHis[0]*3600)+($startTimeHis[1]*60)+$startTimeHis[2])*1000+$startTimeArr[1];
//            $row['text'] = $srtAddessRow[2];
//
//            $srtAddessData[] = $row;
//        }
//        return json($srtAddessData);

        $time = time();
        $secret = '6C5FC7EF1A5F71E7119F763A85E25DB1';
        $param = [
            'text'=>'清晨的阳光透过窗帘，轻轻洒在你的脸庞，温暖而柔和。在这宁静的时刻，我想对你说，愿你的生活如这阳光般明媚，每一天都充满喜悦与幸福。无论何时何地，我都会陪伴在你身旁，为你遮挡风雨，分享欢笑与泪水',
            'timestamp'=>$time,
            'appkey'=>'9EB279303E8A73F33452740E44B703EC',
            'speaker'=>'mercury_yunxi_24k',
            'ignore_limit'=>true,
            'gen_srt'=>true,
            'audio_type'=>'mp3',
            'speed'=>'1.5',
            'volume'=>'10',
        ];
        $param['signature'] = md5($param['appkey'].'+'.$secret.'+'.$time);
        $header = [
            'Content-Type'=>'application/json'
        ];

        $baseUri = 'https://open.mobvoi.com/';
        $guzzle = new Client([
            'base_uri' => $baseUri,
            'timeout'  => 120,
            // https请求
            'verify' => strpos($baseUri, 'https:') == false ? true : false,
        ]);
        $domain = parse_url($baseUri,PHP_URL_HOST);
        $cookie = CookieJar::fromArray([],$domain);
        $data = [
            'headers' => $header,
            'json'    => $param,
            'cookies' => $cookie,
        ];
        $response = $guzzle->post('api/tts/v1', $data);
        //$content = $response->getBody()->getContents();
        file_put_contents(runtime_path('mouyin_tts.mp3'),$response->getBody()->getContents());
        //$content = json_decode($response->getBody()->getContents(),true);
        //var_dump($content);
        $responseHeader = $response->getHeaders();
        return json($responseHeader['srt_address']);
    }

    public function stringReplace()
    {
        $words = ['children','naughty','rape','bust','Vagina','No clothes'];
        $words2 = ['children','naughty','rape','bust','Vagina','No clothes'];
        $words = array_merge($words,$words2);
        return json([$words]);
        $pregs = [];
        foreach($words as $val){
            $pregs[] = ucfirst($val);
            $pregs[] = lcfirst($val);
        }

        $string = ' children The sound of a distant church bell rings through No clothes1 the air';
        $reString = str_replace($pregs,'',$string);

        return json([$reString]);
    }

    public function writerExcelFile()
    {
        $data = [
            [
                'aBookid21',
                'a达人名21',
                'a关键词21',
                'a关键词21',
                'a关键词21',
            ],
            [
                '1786711',
                '2010001620',
                '吞噬星空之时光',
                '吞噬星空之时光',
                '吞噬星空之时光',
            ],
            [
                '1763673',
                '2010001620',
                '豪门继承人拉我去领证',
                '豪门继承人拉我去领证',
                '豪门继承人拉我去领证',
            ]
        ];

        $fileName = runtime_path('qicat_keyword_download.xlsx');
        $result = Spreadsheet::getInstance()->writerExcelFile($data,$fileName);

        $client = new Client([
            'base_uri' => 'https://kol.wtzw.com/',
            'timeout'  => 120,
            // https请求
            'verify' => strpos('https://kol.wtzw.com/', 'https:') == false ? true : false,
        ]);
        // 准备multipart数据
        $multipartData = [
            [
                'name'     => 'file',
                'contents' => fopen($fileName, 'r')
            ]
        ];
        // 准备请求头
        $headers = [
            'X-Qm-Devops-Token'=>config('param.qi_cat_token')
        ];
        // 创建请求
        $request = new \GuzzleHttp\Psr7\Request('POST', 'api/v1/promotion/upload_file', $headers, new MultipartStream($multipartData));
        try {
            // 发送请求
            $response = $client->send($request);

            // 输出响应体
            $data = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);

            $result = [];
            if(!empty($data['data']['address'])){
                $param = [
                    'product_id'=>1,
                    'upload_url'=>$data['data']['address'],
                ];
                $result = Guzzle::post('https://kol.wtzw.com/','api/v1/promotion/add_keywords',$param,$headers,'json');
            }
            return json([$data,$result]);
        } catch (RequestException $e) {
            throw $e;
        } catch (\Throwable $e) {
            throw $e;
        }
    }

    public function generateVideo()
    {
        //$command = 'ffmpeg -i '.runtime_path('ffmpeg_video/%d.png').' -s 1024x1024 -c:v libx264 -pix_fmt yuv420p -t 50 -r 5 '.runtime_path('output.mp4');
        //$command = 'ffmpeg -loop 1 -i '.runtime_path('ffmpeg_video/1.png').' -i '.runtime_path('ffmpeg_video/1.mp3').' -c:v libx264 -c:a aac -b:a 192k -shortest '.runtime_path('output2.mp4');

//        $command ='ffmpeg -loop 1 -t 2 -i '.runtime_path('ffmpeg_video/image/24062416251448_0.png').' -loop 1 -t 2 -i '.runtime_path('ffmpeg_video/image/24062416251448_1.png').' -loop 1 -t 2 -i '.runtime_path('ffmpeg_video/image/24062416251448_2.png').' -loop 1 -t 2 -i '.runtime_path('ffmpeg_video/image/24062416251448_3.png').' -loop 1 -t 2 -i '.runtime_path('ffmpeg_video/image/24062416251448_4.png').' -filter_complex "[0:v]xfade=transition=wipeleft:duration=1:offset=0[v0];[1:v]xfade=transition=wiperight:duration=1:offset=0[v1];[2:v]xfade=transition=circlecrop:duration=1:offset=0[v2];[3:v]xfade=transition=circlecrop:duration=1:offset=0[v3];[v0][v1][v2][v3]concat=n=4:v=1:a=0,format=yuv420p[v]" -map "[v]" -y '.runtime_path('output3.mp4');
//
//        $command = 'ffmpeg -i '.runtime_path('output3.mp4').' -i '.runtime_path('ffmpeg_video/1.mp3').' -i '.runtime_path('ffmpeg_video/2.mp3').' -i '.runtime_path('ffmpeg_video/3.mp3').' -i '.runtime_path('ffmpeg_video/4.mp3').' -filter_complex "[1]adelay=0|2000=[s1];[2]adelay=2500|4500=[s2];[3]adelay=5000|7000=[s3];[4]adelay=7500|9500=[s4];[s1][s2][s3][s4]amix=4[a]" -map 0:v -map "[a]" -c:v copy -c:a aac -strict experimental '.runtime_path('output4.mp4');
//
//        exec($command);

//        $command = "ffmpeg -i ".runtime_path('ffmpeg_video/video_mp3_1719995066960_0.mp4')." -i ".runtime_path('ffmpeg_video/srt/24062416251448_0.srt')." -filter_complex \"subtitles=".runtime_path('ffmpeg_video/srt/24062416251448_0.srt').":force_style='Fontsize=16,PrimaryColour=0xFFFFFF'\" -c:v libx264 -c:a copy  ".runtime_path('ffmpeg_video/video_subtitle_1719995066960_0.mp4');
//        $command = "ffmpeg -i D:/www/video/runtime/ffmpeg_video/video_mp3_1719995066960_0.mp4 -i 24062416251448_0.srt -filter_complex \"subtitles=./runtime/ffmpeg_video/srt/24062416251448_0.srt:force_style='Fontsize=16,PrimaryColour=0xFFFFFF'\" -c:v libx264 -c:a copy  D:/www/video/runtime/ffmpeg_video/video_subtitle_1719995066960_0.mp4";
//        exec($command);

//        return json([$command]);


        $batch = '24070411304327';
        $parts = NovelChapterPartModel::getInstance()->getWhere(['novel_sn'=>'509475','batch'=>$batch])->orderBy('number','asc')->get();
        $data = [];
        foreach($parts as $val){
            $timbreVoiceInfo = json_decode($val['timbre_voice_info'],true);
            $htts = $timbreVoiceInfo[count($timbreVoiceInfo)-1]['end']-$timbreVoiceInfo[0]['start'];
            $tts = round($htts/1000);
            $tts<2 && $tts=2;
            $data[] = [
                'image'=>$val['ai_images1'],
                'tts'=>$tts,
                'htts'=>$htts,
                'content'=>$val['content'],
                'timbre_voice_url'=>$val['timbre_voice_url'],
            ];
        }

        $transitions = ['fade','fadeblack','wipeleft','wiperight','smoothleft','smoothright','wipetl','wipetr'];
        $loops = [];
        $mp3s = [];
        $complex = [];
        $complexMp3 = [];
        $v = [];
        $fix = round(microtime(true)*1000);
        $startTime = 0;
        $s = [];
        $subtitles = [];
        $subtitleContent = '';
        foreach($data as $k=>$val){

            //图像
            $fileName = $batch.'_'.$k.'.png';
            $filePath = runtime_path('ffmpeg_video/image/'.$fileName);
            if(is_file($filePath)==false){
                Common::mkdirs(dirname($filePath));
                file_put_contents($filePath,file_get_contents($val['image']));
            }

            $loops[] = ' -loop 1 -t '.$val['tts'].' -i '.$filePath.' ';

            if($k<(count($data)-1)){
                shuffle($transitions);
                $complex[] = ' ['.$k.':v]xfade=transition='.$transitions[0].':duration=1:offset=1[v'.$k.']; ';
                $v[] = '[v'.$k.']';
            }

            //配音
            $fileName = $batch.'_'.$k.'.mp3';
            $filePath = runtime_path('ffmpeg_video/mp3/'.$fileName);
            if(is_file($filePath)==false){
                Common::mkdirs(dirname($filePath));
                file_put_contents($filePath,file_get_contents($val['timbre_voice_url']));
            }
            $mp3s[] = ' -i '.$filePath.' ';

            $endTime = round($startTime+($val['tts']*1000));
            $complexMp3[] = '['.($k+1).']adelay='.$startTime.'|'.$endTime.'=[s'.($k+1).'];';
            $s[] = '[s'.($k+1).']';

            //字幕
            if($k==0){
                $startT = '00:00:00,000';
            }else{
                $st = floor($startTime/1000);
                $st<10 && $st = '0'.$st;
                $h = $startTime%1000;
                $h = str_pad($h, 3, '0', STR_PAD_LEFT);
                $startT = '00:00:'.$st.','.$h;
            }

            $st = floor($endTime/1000);
            $st<10 && $st = '0'.$st;
            $h = $endTime%1000;
            $h = str_pad($h, 3, '0', STR_PAD_LEFT);
            $endT = '00:00:'.$st.','.$h;
            $subtitleContent .= ($k+1)."\n".$startT." --> ".$endT."\n".$val['content']."\n";

            $k==0 && $startTime = $endTime;
            $k>0 && $startTime = $endTime+1000;
        }

        $fileName = $batch.'.srt';
        $filePath = runtime_path('ffmpeg_video/srt/'.$fileName);
        if(is_file($filePath)==false){
            Common::mkdirs(dirname($filePath));
            file_put_contents($filePath,$subtitleContent);
        }
        $subtitlesFilePath = './runtime/ffmpeg_video/srt/'.$fileName;


        $imageVideo = runtime_path('ffmpeg_video/video_image_'.$fix.'.mp4');
        $command = 'ffmpeg '.implode('',$loops).' -filter_complex "'.implode('',$complex).implode('',$v).'concat=n='.(count($data)-1).':v=1:a=0,format=yuv420p[v]" -map "[v]" -r 30 -vcodec libx264  -y '.$imageVideo;
        exec($command);

//        $mp3Video = runtime_path('ffmpeg_video/video_mp3_'.$fix.'.mp4');
//        //$imageVideo = runtime_path('ffmpeg_video/video_image_1720067055112.mp4');
//        $command = 'ffmpeg -i '.$imageVideo.implode('',$mp3s).'  -filter_complex "'.implode('',$complexMp3).implode('',$s).'amix=inputs='.count($data).':normalize=0[a]" -map 0:v -map "[a]" -c:v copy -c:a aac -strict experimental '.$mp3Video;
//        is_file($imageVideo) && exec($command);
//
//        $subtitleVideo = runtime_path('ffmpeg_video/video_subtitle_'.$fix.'.mp4');
//        //$mp3Video = runtime_path('ffmpeg_video/video_mp3_1720073567862.mp4');
//        $command = 'ffmpeg -i '.$mp3Video.' -i '.$subtitlesFilePath.'  -filter_complex "subtitles='.$subtitlesFilePath.':force_style=\'Fontsize=16,PrimaryColour=0xFFFFFF\'" -c:v libx264 -c:a copy  '.$subtitleVideo;
//        is_file($mp3Video) && exec($command);

//        $command = '';
//        foreach ($mp3s as $k=>$val){
////            //配音
////            $mp3Video = runtime_path('ffmpeg_video/video_mp3_'.$fix.'_'.$k.'.mp4');
////            $command = 'ffmpeg -i '.$imageVideo.$val.'  -filter_complex "'.$complexMp3[$k].'[s1] amix=inputs=1:normalize=0[a]" -map 0:v -map "[a]" -c:v copy -c:a aac -strict experimental '.$mp3Video;
////            exec($command);
////
////
////            //字幕
//            $subtitleVideo = runtime_path('ffmpeg_video/video_subtitle_'.$fix.'_'.$k.'.mp4');
//            //ffmpeg -i input_video.mp4 -i subtitles.srt -filter_complex "subtitles=subtitles.srt:force_style='Fontsize=16,PrimaryColour=0xFFFFFF'" -c:v libx264 -c:a copy output_video.mp4
//            $command = 'ffmpeg -i '.$mp3Video.' -i '.$subtitles[$k].'  -filter_complex "subtitles='.$subtitles[$k].':force_style=\'Fontsize=16,PrimaryColour=0xFFFFFF\'" -c:v libx264 -c:a copy  '.$subtitleVideo;
//            exec($command);
//            $mp3Video = $subtitleVideo;
//
//            if($k==2){
//                break;
//            }
//        }


        return json([$command]);
    }

    public function detectFace()
    {
        $arr = array_filter(explode("|@@|",config('param.meishe_transition_key','')));
        return json($arr);
        $image = 'https://ai-video-1320718644.cos.ap-guangzhou.myqcloud.com/video/prod/stable_diffusion_image/20240708/png/9a362c797f2c7c1073ac.png';
        $result = DetectFaceAdvance::getInstance()->getFaceBody($image);
        return json($result);
    }

    public function matchChinese(Request $request): Response
    {
        $string = "****";
        // 匹配所有的中文字符，包括基本的汉字和扩展的中文字符
//        $pattern = '/[\x{4e00}-\x{9fa5}]+/u';
//        $res = preg_match($pattern, $string, $matches);

        $pattern = '/[a-z|A-Z|0-9]+/';
        $res = preg_match($pattern, $string, $matches);
        var_dump($res);

        return $this->endSuccess($matches);
    }

    public function videoParting()
    {
        $cmd1 = 'ffmpeg -i '.runtime_path('video_part/222.mp4').' -vcodec copy -acodec copy -ss 00:00:01 -to 00:01:00 '.runtime_path('video_part/1.mp4');
        $cmd2 = 'ffmpeg -i '.runtime_path('video_part/222.mp4').' -vcodec copy -acodec copy -ss 00:01:01 -to 00:02:00 '.runtime_path('video_part/2.mp4');
        $cmd3 = 'ffmpeg -i '.runtime_path('video_part/222.mp4').' -vcodec copy -acodec copy -ss 00:02:01 -to 00:03:00 '.runtime_path('video_part/3.mp4');
        exec($cmd1);
        exec($cmd2);
        exec($cmd3);

        return json(['success']);
    }

    public function volcengine()
    {

        $text   = 'The morning sun shines through the curtains, gently shining on your face, warm and soft. In this quiet moment, I want to say to you, may your life be as bright as this sunshine, and may every day be full of joy and happiness. No matter when and where, I will be by your side, shielding you from the wind and rain, sharing laughter and tears';
        $option = [
            'speed'=>'1',
            'volume'=>'50',
            'speaker'=>'BV503_streaming',
        ];
        $result = VolcanoTts::getInstance()->textToVoice($text,$option);
        file_put_contents(runtime_path('volcengine2.mp3'),$result['content']);
        return json([$result['srt_address_data']??'']);

        //        $accessToken = '6HmE0Vyhku1oGr7g_cY4uvhiTwu2_zBI';
//        $param = [
//            'app'   => [
//                'appid'=>'9361166377',
//                'token'=> Common::randString(12,1),
//                'cluster'=>'volcano_tts'
//            ],
//            "user"=>[
//                "uid"=> Common::randString(12,1)
//            ],
//            "audio"=>[
//                "voice_type"=>'BV437_streaming',
//                "encoding"=>"mp3",
//                "speed_ratio"=> 1.0,
//                "volume_ratio"=>1.0,
//                "pitch_ratio"=>1.0,
//            ],
//            "request"=>[
//                "reqid"=> Common::getRequestId(),
//                "text"=> $text,
//                "text_type"=>"plain",
//                "operation"=>"query",
//                "with_frontend"=>1,
//                "frontend_type"=>"unitTson"
//            ],
//        ];
//        $headers = [
//            'Authorization'=>'Bearer;'.$accessToken,
//        ];
//        $result = Guzzle::post('https://openspeech.bytedance.com/','api/v1/tts',$param,$headers,'json');
//        var_dump($result['addition']['description']??'fsdfsdfsd');
//        var_dump($result['addition']['frontend']??'wwwwwwwwwwwwwwwwww');
//        file_put_contents(runtime_path('volcengine.mp3'), file_get_contents('data:audio/mpeg;base64,'.$result['data']));
//        file_put_contents(runtime_path('volcengine.log'), json_encode($result,256)."\n\n",8);
        //return json($result ?? []);
    }

    public function getBucketListObject()
    {
        //sleep(6);
        $withHeightMap = [];
        foreach (Constant::OVERSEA_VIDEO_RATE_MAP as $rate=>$val){
            $withHeightMap['rate_'.$val] = $rate;
        }
        return json($withHeightMap ?? []);

        $result = TencentCos::getInstance()->getBucketListObject('video/test/upload/video/20240812/20240812/mp4/');
        $voiceRe = [];

        if(!empty($result['Contents'])){
            $marker = urldecode($result['NextMarker']);
            var_dump($marker);
            $url = 'https://'.$result['Location'].$result['Contents'][1]['Key'];
            $fullPath = runtime_path('video_data.mp4');
            file_put_contents($fullPath,file_get_contents($url));
            $voiceRe= (new GetID3())->analyze($fullPath);
//            var_dump($withHeightMap[$voiceRe['video']['resolution_x'].'_'.$voiceRe['video']['resolution_y']]);
//            var_dump($voiceRe['video']['resolution_x']);
//            var_dump($voiceRe['video']['resolution_y']);
        }
        return json($voiceRe ?? []);
    }

    public function uploadLoadBgm()
    {
        $contents = json_decode(file_get_contents(runtime_path('bgm.txt')), true);
        $insert = [];
        foreach ($contents['bgmList'] as $k=>$val){
            $file = runtime_path('bgm'.$k.'.mp3');
            file_put_contents($file,file_get_contents($val['url']));
            $voiceRe= (new GetID3)->analyze($file);
            if(!empty($voiceRe['playtime_seconds'])){
                $res = TencentCos::getInstance()->uploadLocalFile($file,'bgm');

                $insert[] = [
                    'name'=>$val['name'],
                    'music_url'=>"https://".$res['Location'],
                    'tts'=>$voiceRe['playtime_seconds'],
                    'size'=>$voiceRe['filesize'],
                    'lang'=>'英文',
                    'tags'=>$val['groupName'],
                    'status'=>0
                ];
            }
            unlink($file);
        }
        $insert && BackgroundMusicModel::getInstance()->insert($insert);

        return json([]);
    }

    public function publicRabbitmqQueue()
    {
        $data = ['id'=>1,'request_id'=>Common::getRequestId(),'time'=>date('Y-m-d H:i:s')];
        RabbitMq::getInstance()->publicQueue('test_queue',$data);
        return json(['public_queue']);
    }

}